package cnki.kg.demo.datatransfer;

import com.mysql.cj.jdbc.result.ResultSetImpl;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DataReader {
    public static  List<Map<String,Object>> readData(Connection conn,String driverName,String table,Integer pageIndex,Integer pageSize) throws SQLException {
        String contentSql = String.format("SELECT * FROM %s limit %s,%s",table, pageIndex * pageSize, pageSize);
        return executeQuery(conn,contentSql);
    }
    public static Integer executeScalar(Connection conn,String sql) throws SQLException {
        Integer result = null;
        ResultSet rs = null;
        Statement pst = null;
        try {
            pst = conn.createStatement();
            rs = pst.executeQuery(sql);
            rs.next();
            result = rs.getString(1)!=null?Integer.parseInt(rs.getString(1)):0;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(rs!=null){
                rs.close();
            }
        }
        return result;
    }
    public static List<Map<String, Object>> executeQuery(Connection conn,String sql) {
        List<Map<String, Object>> result = new ArrayList<>();
        try {
            ResultSetImpl krs = null;
            Statement pst = null;
            pst = conn.createStatement();
            ResultSet rs = pst.executeQuery(sql);
            ResultSetMetaData md = rs.getMetaData(); // 得到结果集的结构信息，比如字段数、字段名等
            int columnCount = md.getColumnCount(); // 返回此 ResultSet 对象中的列数
            while (rs.next()) {
                Map<String, Object> map = new HashMap<String, Object>(columnCount);
                for (int i = 1; i <= columnCount; i++) {
                    String cloumnName = "";
                    cloumnName = md.getColumnName(i);
                    String value = "";
                    if (rs.getString(i) != null) {
                        value = String.valueOf(rs.getString(i));// 获取字段值
                    }
                    map.put(cloumnName, value);
                }
                result.add(map);
            }
            rs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
